package com.myz.app.controller;

import com.myz.app.entity.User;
import com.myz.app.service.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @author maoyz
 */
@Controller
public class LoginControl {

  private final static Logger logger = LoggerFactory.getLogger(LoginControl.class);

  @Resource
  ShiroService service;


  // @ExceptionHandler({UnauthorizedException.class})
  // @RequestMapping(value="/login",method=RequestMethod.GET)
  // public String loginForm(Model model){
  //     model.addAttribute("user", new User());
  //     return "/login";
  // }

  /**
   * 仅做测试使用
   */
  @RequestMapping("/testAnnotation")
  public String testAnnotation(HttpSession session) {
    session.setAttribute("shiroSession", "hello");
    service.testAnnotation();
    return "redirect:/index.jsp";
  }

  @GetMapping(value = "/login")
  public String login() {
    logger.info("===================用户进入了ShiroController的/login.html");
    return "redirect:login.jsp";
  }

  /**
   * 登录
   */
  @PostMapping(value = "/login")
  public String login(User user, HttpServletRequest request, Model model) {
    logger.info("用户名:" + user.getUsername() + "---密码:" + user.getPassword());
    String captcha = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
    logger.debug("captcha" + user.getCaptcha());
    String msg;
    // 获取当前用户
    Subject currentUser = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
    //　记住我功能
    token.setRememberMe(true);

    try {
      //
      currentUser.login(token);
      if (currentUser.isAuthenticated()) {
        request.getSession().setAttribute("user", user);
        SavedRequest savedRequest = WebUtils.getSavedRequest(request);
        // 获取保存的URL
        if (savedRequest == null || savedRequest.getRequestUrl() == null) {
          return "/admin/home";
        } else {
          //String url = savedRequest.getRequestUrl().substring(12, savedRequest.getRequestUrl().length());
          return "forward:" + savedRequest.getRequestUrl();
        }
      }
    } catch (IncorrectCredentialsException e) {
      msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
      model.addAttribute("message", msg);
      System.out.println(msg);
    } catch (ExcessiveAttemptsException e) {
      msg = "登录失败次数过多";
      model.addAttribute("message", msg);
      System.out.println(msg);
    } catch (LockedAccountException e) {
      msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
      model.addAttribute("message", msg);
      System.out.println(msg);
    } catch (DisabledAccountException e) {
      msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
      model.addAttribute("message", msg);
      System.out.println(msg);
    } catch (ExpiredCredentialsException e) {
      msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
      model.addAttribute("message", msg);
      System.out.println(msg);
    } catch (UnknownAccountException e) {
      msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
      model.addAttribute("message", msg);
      System.out.println(msg);
    } catch (UnauthorizedException e) {
      msg = "您没有得到相应的授权！" + e.getMessage();
      model.addAttribute("message", msg);
      System.out.println(msg);
    }
    return "/login";
  }

  @RequestMapping("/logout")
  public String logout(HttpServletRequest request, Model model) {
    logger.info("=======================用户" + request.getSession().getAttribute("user") + "退出了系统");
    SecurityUtils.getSubject().logout();
    return "redirect:login.html";
  }

}
